package cn.xiuxius.embedded;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;

public class EasyStcProjectUtils {
    private static final Pattern TASK_PATTERN = Pattern.compile("_task_\\s*\\d+");

    private static VirtualFile getProjectBaseDir(@NotNull Project project) {
        String basePath = project.getBasePath();
        if (basePath == null) return null;
        return LocalFileSystem.getInstance().findFileByPath(basePath);
    }

    public static boolean containsTaskPattern(VirtualFile file) {
        try {
            String content = VfsUtil.loadText(file);
            return TASK_PATTERN.matcher(content).find();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isEasyStcProject(@NotNull Project project) {
        VirtualFile baseDir = getProjectBaseDir(project);
        return baseDir != null && baseDir.findChild("easy-stc.yml") != null;
    }

    public static boolean isRtx51Enabled(Project project) {
        VirtualFile baseDir = getProjectBaseDir(project);
        if (baseDir == null) return false;

        VirtualFile configFile = baseDir.findFileByRelativePath("easy-stc.yml");
        if (configFile != null) {
            try (InputStream inputStream = configFile.getInputStream()) {
                Yaml yaml = new Yaml();
                Map<String, Object> root = yaml.load(inputStream);
                if (root == null) return false;

                // 取keilProject节点
                Object keilProjectObj = root.get("keilProject");
                if (!(keilProjectObj instanceof Map<?, ?> keilProject)) return false;

                Object rtosObj = keilProject.get("rtos");
                if (rtosObj == null) return false;

                String rtosValue = rtosObj.toString().toUpperCase();
                return "RTX_51_TINY".equals(rtosValue) || "RTX_51_FULL".equals(rtosValue);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean isEasyStcWithRtx51(Project project) {
        return isEasyStcProject(project) && isRtx51Enabled(project);
    }

    /**
     * 读取项目根目录下 easy-stc.yml 配置文件中 keilProject.groups，返回组名称列表（user, lib, drive等）
     *
     * @param project 当前打开的项目
     * @return 组名称列表，找不到返回空列表
     */
    public static Map<String, String> getGroupsWithPaths(@NotNull Project project) {
        VirtualFile baseDir = LocalFileSystem.getInstance().findFileByPath(project.getBasePath());
        if (baseDir == null) return Collections.emptyMap();

        VirtualFile configFile = baseDir.findChild("easy-stc.yml");
        if (configFile == null || !configFile.exists()) return Collections.emptyMap();

        try (InputStream is = configFile.getInputStream()) {
            Yaml yaml = new Yaml();
            Map<String, Object> root = yaml.load(is);
            if (root == null) return Collections.emptyMap();

            Object keilProjectObj = root.get("keilProject");
            if (!(keilProjectObj instanceof Map<?, ?> keilProject)) return Collections.emptyMap();

            // 获取 rootPath，如果没有设置则默认为项目根目录
            String rootPath = ".";
            Object rootPathObj = keilProject.get("rootPath");
            if (rootPathObj instanceof String) {
                rootPath = (String) rootPathObj;
            }

            Object groupsObj = keilProject.get("groups");
            if (!(groupsObj instanceof List<?> groupsList)) return Collections.emptyMap();

            Map<String, String> result = new LinkedHashMap<>(); // 保持顺序
            for (Object groupEntry : groupsList) {
                if (groupEntry instanceof Map<?, ?> groupMap) {
                    for (Map.Entry<?, ?> entry : ((Map<?, ?>) groupMap).entrySet()) {
                        String groupName = entry.getKey() != null ? entry.getKey().toString() : null;
                        if (groupName != null) {
                            // 处理组配置中的 path
                            String groupPath = "."; // 默认路径
                            if (entry.getValue() instanceof Map<?, ?> groupConfig) {
                                Object pathObj = groupConfig.get("path");
                                if (pathObj instanceof String) {
                                    groupPath = (String) pathObj;
                                }
                            }

                            // 组合 rootPath 和 groupPath，生成完整相对路径
                            String fullPath = Paths.get(rootPath, groupPath).normalize().toString();
                            result.put(groupName, fullPath);
                        }
                    }
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyMap();
        }
    }


}
